require 'singleton'

module Merge
  
  class Service
    include Singleton
    
    public
    
    attr_accessor :rank
    
    def find_service(services)
      candidate = services.select {|s| service_ok?(s) }
      size = candidate.length
      ret = nil
      case size
        when 1
        ret = candidate[0]
        when 0
        ret = nil
      else
        similar = candidate.select {|s| service_similar_to_user?(s) }
        ret = similar[0] if similar.length > 0
      end
      
      ret 
    end
    
    def service_ff_id
      raise NotImplementedError.new "Subclass must implents this method!!"
    end
    
    def rank
      1
    end
    
    protected
    
    def service_similar_to_user?(s)
      s.user.ff_id
    end
    
    def service_similar_to_user?(s)
      s.username_on_service == s.user.ff_id
    end
    
    def service_ok?(s)
      (s.ff_id == self.service_ff_id) && (!s.crawl.nil?) && (s.crawl.status == 200) && (!s.crawl.data.nil?)
    end
    
    protected
    
    def initialize()
      rank = 0
    end
  end
  
end